package net.lookyou.boot.demo.config.security.provider;

import net.lookyou.boot.demo.config.security.service.PassWordUserDetailsService;
import net.lookyou.boot.demo.config.security.token.PassWordAuthenticationToken;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 普通自定义认证器
 */
@Component
public class PassWordAuthenticationProvider implements AuthenticationProvider {

    @Resource
    private PassWordUserDetailsService passWordUserDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Object username = authentication.getPrincipal();
        Object password = authentication.getCredentials();
        UserDetails userDetails = passWordUserDetailsService.loadUserByUsername(username.toString());
        return new PassWordAuthenticationToken(username, password, userDetails.getAuthorities());

    }

    @Override
    public boolean supports(Class<?> aClass) {
        /**
         * providerManager会遍历所有
         * SecurityConfig中注册的provider集合
         * 根据此方法返回true或false来决定由哪个provider
         * 去校验请求过来的authentication
         */
        return (PassWordAuthenticationToken.class.isAssignableFrom(aClass));

    }
}
